// 主收费项维护界面 --- 价格信息
import React from 'react';
import { Form, Row, Col, Button, Input, Select, DatePicker, message } from 'antd';
import store from 'store';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx';
import { $http } from 'containers/config/https';
import Moment from 'moment';

const { TextArea } = Input;
const { Option } = Select;

class MTMPriceInformation extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userInfo: {}, // 收费项选中行数据
            tableData: [], // 价格列表数据
            rowId: '', // 选中行ID
            rowData: {}, // 选中行数据
            otherSelectData: {}, // 费别,等级,单位,地区下拉框数据
            itemID: '', // 收费项ID
            hospID: '', // 医院下拉框id
            hospSelectData: [], // 医院下拉框数据
            effectiveflag: 'Y',
            payOffData: [], // 费别数据
        };
        this.columns = [
            { title: '费别', dataIndex: 'priceAdmReasonDesc', key: '1', width: '100px', align: "center" },
            { title: '价格', dataIndex: 'price', key: '2', width: '100px', align: "center" },
            { title: '开始日期', dataIndex: 'priceStDate', key: '3', width: '100px', align: "center" },
            { title: '结束日期', dataIndex: 'priceEndDate', key: '4', width: '100px', align: "center" },
            { title: '级别', dataIndex: 'priceGradeDesc', key: '5', width: '100px', align: "center" },
            { title: '医院', dataIndex: 'pricehospDesc', key: '6', width: '150px', align: "center" },
            { title: '物价依据', dataIndex: 'priceChargeCode', key: '7', width: '150px', align: "center" },
            { title: '备注', dataIndex: 'priceRemarks', key: '8', width: '150px', align: "center" },
            { title: '创建日期', dataIndex: 'createDate', key: '9', width: '100px', align: "center" },
            { title: '创建时间', dataIndex: 'createTime', key: '10', width: '100px', align: "center" },
            { title: '创建人员', dataIndex: 'createUserDesc', key: '11', width: '100px', align: "center" },
        ]
    }

    componentDidMount() {
        this.props.onRef(this)
        this.getTableListData()
        this.initData(); // 初始化数据

    }

    componentWillReceiveProps(props) {
        if (props.rowId !== this.state.itemID) {
            this.setState({ itemID: props.rowId }, () => {
                this.getTableListData();
            })

        }
        if (props.rowData !== this.state.userInfo) {
            this.setState({ userInfo: props.rowData })

        }
    }
    initData = () => {
        if (this.props.otherSelectData) {
            if (this.props.otherSelectData !== this.state.otherSelectData) {
                this.setState({ otherSelectData: this.props.otherSelectData })
            }
        } else {
            this.getOtherSelectData();
        }
        if (this.props.hospSelectData && this.props.hospSelectData.length > 0) {
            if (this.props.hospSelectData !== this.state.hospSelectData) {
                this.setState({ hospSelectData: this.props.hospSelectData })
            }
        } else {
            this.getHospSelectData();
        }
        if (this.props.rowId !== this.state.itemID) {
            this.setState({ itemID: this.props.rowId }, () => {
                this.getTableListData();
            })
        }
        if (this.props.rowData !== this.state.userInfo) {
            this.setState({ userInfo: this.props.rowData })
        }
    }

    // 1.1.5.费别，等级,单位,地区
    getOtherSelectData = () => {
        let data = {
            params: [{}]
        }
        $http.post('urlS', this, {
            code: "05100082",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ otherSelectData: res })
                }
            }
        })
    }

    //.费别
    payOffData = () => {
        let data = {
            params: [{
                "hospID": this.state.hospID,
            }]
        }
        $http.post('urlS', this, {
            code: "05100129",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ payOffData: res.data })
                }
            }
        })
    }

    // 获取医院下拉框数据
    getHospSelectData = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {
            params: [{
                logonGroupID: user && user.groupID ? user.groupID : '', // 登录的角色ID
                logonHospID: user && user.hospID ? user.hospID : '', // 登录的医院
                dataType: 'combo', //
            }]
        }
        $http.post('urlS', this, {
            code: "05100046",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ hospSelectData: res.Hosp });
                }
            }
        })
    }

    // 获取价格列表数据
    getTableListData = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let { hospID, effectiveflag, itemID } = this.state;
        let data = {
            params: [{
                itemID, // 收费项ID
                hospID: hospID ? hospID : this.state.userInfo.itemHospID, // 医院下拉框id
                effectiveflag: effectiveflag, // 条件
                logonGroupID: user && user.groupID ? user.groupID : '', // 登录的角色ID
                logonHospID: user && user.hospID ? user.hospID : '', // 登录的医院
            }]
        }
        // 数据加载成功关闭loading
        this.child.handleLoading();
        $http.post('urlS', this, {
            code: "05100022",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let tableData = res.result.Data ? res.result.Data : [];
                    for (var i = 0; i < tableData.length; i++) {
                        tableData[i].key = i + 1
                    }
                    this.setState({ tableData });
                }
            }
        })
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 操作行
    onClickRowPublic = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.rowId === '') {
                    // 保存行数据以及ID
                    this.setState({ rowId: record.ID, rowData: record }, () => {
                        this.props.form.resetFields(); // 重置表单
                    });
                } else {
                    if (this.state.rowId !== record.ID) {
                        this.setState({ rowId: record.ID, rowData: record }, () => {
                            this.props.form.resetFields(); // 重置表单
                        });
                    } else {
                        this.setState({ rowId: "", rowData: {} }, () => {
                            this.props.form.resetFields(); // 重置表单
                        });
                    }
                }
            }
        }
    }

    // 选中行操作
    setRowClassNamePublic = (record) => {
        return record.ID === this.state.rowId ? 'clickRowStyle' : '';
    }

    // 保存
    handleSave = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            // 验证成功
            if (errors === null) {
                values.logonGroupID = user && user.groupID ? user.groupID : '';
                values.logonHospID = user && user.hospID ? user.hospID : '';
                values.updateUserID = user && user.userID ? user.userID : '';
                values.itemID = this.state.itemID ? this.state.itemID : '';
                values.priceID = this.state.rowId ? this.state.rowId : '';
                values.priceStDate = values.priceStDate ? Moment(values.priceStDate).format('YYYY-MM-DD') : undefined; // 开始日期
                values.priceEndDate = values.priceEndDate ? Moment(values.priceEndDate).format('YYYY-MM-DD') : undefined; // 结束日期
                let data = {
                    params: []
                }

                let code = values.priceID ? '05100047' : '05100093';
                data.params.push(values)
                $http.post('urlADS', this, {
                    code: code,
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            // 成功提示
                            if (code === '05100047') {
                                message.success('编辑成功');
                            } else {
                                message.success('新增成功');
                            }
                            this.getTableListData();
                        }
                    }
                })
            }
        })
    }

    //重置表单
    resetFields = () => {
        this.setState({ rowId: "", rowData: {} }); // 清空选中数据
        this.props.form.resetFields();
    }

    // 选择医院重新查询列表
    handlePriceHosp = (e) => {
        this.setState({ hospID: e }, () => {
            this.getTableListData()
            this.payOffData() // 费别
            this.props.form.setFieldsValue({
                'priceAdmReasonID': '',
            });
        })
    }

    // 选择条件重新查询列表
    handleEffectiveflag = (e) => {
        this.setState({ effectiveflag: e }, () => {
            this.getTableListData()
        })
    }

    // 开始日期选择限制
    disabledStDate(current) {
        /**
         * @ByYQY: 对收费项维护的开始日期限制做判断
         * Create 2022-01-12
         */
        let { tableData } = this.state;
        if (tableData && tableData.length > 0) {
            // 开始日期不能选择今天和之前的日期
            return current && current < Moment().endOf('day');
        }
    }

    // 结束日期选择限制
    disabledEndDate(current) {
        // 结束日期不能选择今天之前的日期
        return current && current < Moment(new Date(Date.parse(new Date()) - 86400000)).endOf('day');
    }

    render() {
        let { height } = this.props;
        let { tableData, userInfo, hospSelectData, rowData, otherSelectData, rowId } = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput = {
            labelCol: {
                xs: { span: 12 },
                sm: { span: 12 },
                md: { span: 12 },
                lg: { span: 12 },
                xl: { span: 10 },
                xxl: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 12 },
                sm: { span: 12 },
                md: { span: 12 },
                lg: { span: 12 },
                xl: { span: 14 },
                xxl: { span: 18 },
            },
        };
        const formItemTextArea = {
            labelCol: {
                xs: { span: 6 },
                sm: { span: 6 },
                md: { span: 6 },
                lg: { span: 6 },
                xl: { span: 5 },
                xxl: { span: 3 },
            },
            wrapperCol: {
                xs: { span: 18 },
                sm: { span: 18 },
                md: { span: 18 },
                lg: { span: 18 },
                xl: { span: 19 },
                xxl: { span: 21 },
            },
        }
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: tableData,
            // 表格的宽度
            x: 1300,
            y: height ? height : store.getState().tableHeight.y - 177,
            height: height ? (height + 50 + 'px') : store.getState().tableHeight.y - 127 + 'px',
            isOnRow: true,
            rowClassName: true
        }

        // 医院
        let hospOption = hospSelectData && hospSelectData.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 费别
        let feeOption = this.state.payOffData && this.state.payOffData.map((item, index) => {
            return (<Option key={index} title={item.descripts} value={item.id}>{item.descripts}</Option>)
        })
        // 等级
        let gradeOption = otherSelectData.GradeData && otherSelectData.GradeData.map((item, index) => {
            return (<Option key={index} title={item.Descripts} value={item.ID}>{item.Descripts}</Option>)
        })
        return (
            <div style={{ marginTop: '12px' }}>
                <Form>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="医院：" {...formItemInput}>
                                {getFieldDecorator('pricehospID', {
                                    initialValue: rowData.pricehospID ? rowData.pricehospID : (userInfo.itemHospID ? userInfo.itemHospID : undefined),
                                    rules: [{ required: true, message: '请选择医院' }]
                                })(
                                    <Select disabled={rowId ? true : false} onSelect={this.handlePriceHosp} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                                        {hospOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="条件：" {...formItemInput}>
                                {getFieldDecorator('effectiveflag', {
                                    initialValue: rowData.effectiveflag ? rowData.effectiveflag : 'Y',
                                })(
                                    <Select onSelect={this.handleEffectiveflag} showSearch allowClear placeholder="请选择" disabled={rowId ? true : false}>
                                        <Option value="Y" title="有效价格">有效价格</Option>
                                        <Option value="Q" title="当前价格">当前价格</Option>
                                        <Option value="N" title="全部">全部</Option>
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="费别：" {...formItemInput}>
                                {getFieldDecorator('priceAdmReasonID', {
                                    initialValue: rowData.priceAdmReasonID ? rowData.priceAdmReasonID : undefined,
                                    rules: [{ required: true, message: '请选择费别' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" disabled={rowId ? true : false}>
                                        {feeOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>

                    </Row>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="价格：" {...formItemInput}>
                                {getFieldDecorator('price', {
                                    initialValue: rowData.price ? rowData.price : undefined,
                                    rules: [{ required: true, message: '请选择价格' }]
                                })(
                                    <Input placeholder="请输入" disabled={rowId ? true : false} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={16}>
                            <Form.Item label="物价依据" {...formItemTextArea}>
                                {getFieldDecorator('priceChargeCode', {
                                    initialValue: rowData.priceChargeCode ? rowData.priceChargeCode : undefined,
                                })(
                                    <TextArea rows={1} />
                                )}
                            </Form.Item>
                        </Col>

                    </Row>
                    <Row gutter={16}>

                        <Col span={8}>
                            <Form.Item label="等级：" {...formItemInput}>
                                {getFieldDecorator('priceGradeID', {
                                    initialValue: rowData.priceGradeID ? rowData.priceGradeID : undefined,
                                    rules: [{ required: true, message: '请选择等级' }]
                                })(
                                    <Select showSearch allowClear placeholder="请选择" disabled={rowId ? true : false}>
                                        {gradeOption}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={16}>
                            <Form.Item label="备注：" {...formItemTextArea}>
                                {getFieldDecorator('priceRemarks', {
                                    initialValue: rowData.priceRemarks ? rowData.priceRemarks : undefined,
                                })(
                                    <TextArea rows={1} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="开始日期" {...formItemInput}>
                                {getFieldDecorator('priceStDate', {
                                    initialValue: rowData.priceStDate ? Moment(rowData.priceStDate, 'YYYY-MM-DD') : undefined,
                                    rules: [{ required: true, message: '请选择开始日期' }]
                                })(
                                    <DatePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        disabled={rowData.priceStDate ? true : false}
                                        disabledDate={(current) => this.disabledStDate(current)}
                                    />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="结束日期" {...formItemInput}>
                                {getFieldDecorator('priceEndDate', {
                                    initialValue: rowData.priceEndDate ? Moment(rowData.priceEndDate, 'YYYY-MM-DD') : undefined,
                                })(
                                    <DatePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        disabled={rowData.priceEndDate ? true : false}
                                        disabledDate={this.disabledEndDate}
                                    />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8} style={{ textAlign: 'right' }}>
                            <Button type="primary" style={{ marginRight: '12px' }} onClick={this.handleSave}>{rowId ? '编辑' : '新增'}</Button>
                            <Button onClick={this.resetFields}>重置</Button>
                        </Col>
                    </Row>
                </Form>
                <div className="table-body-height">
                    <PubilcTablePagination
                        param={param}
                        handelThis={this}
                        onRef={this.onRef}
                        onClickRowPublic={this.onClickRowPublic}
                        setRowClassNamePublic={this.setRowClassNamePublic}
                    />
                </div>
            </div>
        )
    }
};
const MTMPriceInformationForm = Form.create()(MTMPriceInformation);
export default MTMPriceInformationForm;
